package cn.com.agameofthrones.AGoTLCGCards.Fragment;

import cn.com.agameofthrones.AGoTLCGCards.AGoTContentProvider;
import cn.com.agameofthrones.AGoTLCGCards.R;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class SearchResultFragment extends ListFragment {
	//private SimpleCursorAdapter mSearchResultAdapter;
	private String mWhereClause;
	
	
	public SearchResultFragment(SimpleCursorAdapter ap){
		//mSearchResultAdapter=ap;
	}
	
	public SearchResultFragment(String where_clause){
		mWhereClause=where_clause;
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
	        super.onActivityCreated(savedInstanceState);
	        
	        String[] columns = new String[] {  
        			"_id", "title",
        			"type_name","set_name"};
        	int[] to = new int[] {
        			R.id.search_result_card_id, R.id.search_result_title,
        			R.id.search_result_type,  R.id.search_result_expansion };
           
            Cursor search_result_cursor=getActivity().managedQuery(
            		AGoTContentProvider.SEARCH_CARDS_URI, columns, mWhereClause, null, null);
            
            SimpleCursorAdapter search_result_list_adapter=new SimpleCursorAdapter(getActivity(),
    				R.layout.search_result_row1, search_result_cursor,columns,to);
            
            
	        //add a header for result status
			TextView tv_result_status=new TextView(getActivity());
			Resources res = getResources();
			String result_status_text = String.format(res.getString(R.string.search_result_status), 
					search_result_list_adapter.getCount());
			tv_result_status.setText(result_status_text);
			
		    this.getListView().addHeaderView(tv_result_status);
		    
		    setListAdapter(search_result_list_adapter);
	  }
	
	@Override
	public void onListItemClick (ListView l, View v, int position, long id){
	    Intent intent = new Intent();
        intent.setClass(getActivity(), SingleCardActivity.class);
        intent.putExtra("cn.com.agameofthrones.AGoTLCGCards.search_sql", mWhereClause);
        intent.putExtra("cn.com.agameofthrones.AGoTLCGCards.current_position", position-1);//position is 1-based index
        startActivity(intent);
	}
	   
}